<template>
    <div class="app-container">
        <el-page-header @back="goBack" :content="'碾米机详情'" class="page-header">
        </el-page-header>
        <div class="control-grid">
            <div v-for="(item, index) in controlItems" :key="index" class="control-item">
                <div class="item-title">{{ item.name }}</div>
                <div class="item-content">
                    <el-input-number
                        v-model="item.value"
                        :min="0"
                        controls-position="right"
                        size="small"
                    />
                   <div style="display:flex;align-items: center;justify-content: center">
                       <el-button
                           type="primary"
                           size="small"
                           @click="handleStepRead({
                            propertyId: item.propertyId,
                            index: index
                        })"
                           :loading="item.loading"
                       >
                           读取
                       </el-button>
                       <el-button
                           type="primary"
                           size="small"
                           @click="handleStepSubmit({
                            value: item.value,
                            propertyId: item.propertyId,
                            index: index
                        })"
                           :loading="item.loading"
                       >
                           保存
                       </el-button>
                   </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { listInstanceProperty, instanceFunctionInvoke, getDeviceProduct } from '@/api/device/product'
import { genUUID } from '@/utils/ruoyi'

export default {
    name: 'index',
    data() {
        return {
            webClientId: genUUID(),
            productId: '',
            deviceId: '',
            controlItems: [
                // 开启项
                {
                    name: '粉碎机开',
                    value: null,
                    propertyId: '300',
                    loading: false,
                    timer: null
                },
                {
                    name: '碾米机开',
                    value: null,
                    propertyId: '301',
                    loading: false,
                    timer: null
                },
                {
                    name: '砻谷机开',
                    value: null,
                    propertyId: '302',
                    loading: false,
                    timer: null
                },
                {
                    name: '风提升电机开',
                    value: null,
                    propertyId: '303',
                    loading: false,
                    timer: null
                },
                {
                    name: '去石机电机开',
                    value: null,
                    propertyId: '304',
                    loading: false,
                    timer: null
                },
                {
                    name: '重力筛电机开',
                    value: null,
                    propertyId: '305',
                    loading: false,
                    timer: null
                },
                {
                    name: '碎米筛电机开',
                    value: null,
                    propertyId: '306',
                    loading: false,
                    timer: null
                },
                {
                    name: '谷斗入料气缸开',
                    value: null,
                    propertyId: '307',
                    loading: false,
                    timer: null
                },
                {
                    name: '砻谷下料气缸开',
                    value: null,
                    propertyId: '308',
                    loading: false,
                    timer: null
                },
                {
                    name: '重力筛下白米斗气缸1开',
                    value: null,
                    propertyId: '309',
                    loading: false,
                    timer: null
                },
                {
                    name: '重力筛下白米斗气缸2开',
                    value: null,
                    propertyId: '310',
                    loading: false,
                    timer: null
                },
                {
                    name: '白米斗下料气缸开',
                    value: null,
                    propertyId: '311',
                    loading: false,
                    timer: null
                },
                {
                    name: '砻谷出重力筛气缸开',
                    value: null,
                    propertyId: '312',
                    loading: false,
                    timer: null
                },
                {
                    name: '重力筛回砻谷机气缸开',
                    value: null,
                    propertyId: '313',
                    loading: false,
                    timer: null
                },
                {
                    name: '砻谷机止料气缸开',
                    value: null,
                    propertyId: '314',
                    loading: false,
                    timer: null
                },
                {
                    name: '砻谷入白米斗气缸开',
                    value: null,
                    propertyId: '315',
                    loading: false,
                    timer: null
                },
                // 关闭项
                {
                    name: '粉碎机关',
                    value: null,
                    propertyId: '316',
                    loading: false,
                    timer: null
                },
                {
                    name: '碾米机关',
                    value: null,
                    propertyId: '317',
                    loading: false,
                    timer: null
                },
                {
                    name: '砻谷机关',
                    value: null,
                    propertyId: '318',
                    loading: false,
                    timer: null
                },
                {
                    name: '风提升电机关',
                    value: null,
                    propertyId: '319',
                    loading: false,
                    timer: null
                },
                {
                    name: '去石机电机关',
                    value: null,
                    propertyId: '320',
                    loading: false,
                    timer: null
                },
                {
                    name: '重力筛电机关',
                    value: null,
                    propertyId: '321',
                    loading: false,
                    timer: null
                },
                {
                    name: '碎米筛电机关',
                    value: null,
                    propertyId: '322',
                    loading: false,
                    timer: null
                },
                {
                    name: '谷斗入料气缸关',
                    value: null,
                    propertyId: '323',
                    loading: false,
                    timer: null
                },
                {
                    name: '砻谷下料气缸关',
                    value: null,
                    propertyId: '324',
                    loading: false,
                    timer: null
                },
                {
                    name: '重力筛下白米斗气缸1关',
                    value: null,
                    propertyId: '325',
                    loading: false,
                    timer: null
                },
                {
                    name: '重力筛下白米斗气缸2关',
                    value: null,
                    propertyId: '326',
                    loading: false,
                    timer: null
                },
                {
                    name: '白米斗下料气缸关',
                    value: null,
                    propertyId: '327',
                    loading: false,
                    timer: null
                },
                {
                    name: '砻谷出重力筛气缸关',
                    value: null,
                    propertyId: '328',
                    loading: false,
                    timer: null
                },
                {
                    name: '重力筛回砻谷机气缸关',
                    value: null,
                    propertyId: '329',
                    loading: false,
                    timer: null
                },
                {
                    name: '砻谷机止料气缸关',
                    value: null,
                    propertyId: '330',
                    loading: false,
                    timer: null
                },
                {
                    name: '砻谷入白米斗气缸关',
                    value: null,
                    propertyId: '331',
                    loading: false,
                    timer: null
                },
                {
                    name: '时间模式-谷斗入料气缸关',
                    value: null,
                    propertyId: '332',
                    loading: false,
                    timer: null
                },
                {
                    name: '时间模式-重力筛气缸1关',
                    value: null,
                    propertyId: '334',
                    loading: false,
                    timer: null
                },
                {
                    name: '时间模式-重力筛电机关',
                    value: null,
                    propertyId: '336',
                    loading: false,
                    timer: null
                },
                {
                    name: '时间模式-碾米机开',
                    value: null,
                    propertyId: '337',
                    loading: false,
                    timer: null
                },
                {
                    name: '时间模式-少料',
                    value: null,
                    propertyId: '340',
                    loading: false,
                    timer: null
                },
                {
                    name: '时间模式-少料-多料',
                    value: null,
                    propertyId: '341',
                    loading: false,
                    timer: null
                },
                {
                    name: '时间模式-多料-少料',
                    value: null,
                    propertyId: '342',
                    loading: false,
                    timer: null
                },
                {
                    name: '时间模式-少料-回尾',
                    value: null,
                    propertyId: '343',
                    loading: false,
                    timer: null
                },
                {
                    name: '时间模式-回尾',
                    value: null,
                    propertyId: '344',
                    loading: false,
                    timer: null
                },
                {
                    name: '初始少料传感器1故障',
                    value: null,
                    propertyId: '345',
                    loading: false,
                    timer: null
                },
                {
                    name: '少料多料传感器2故障',
                    value: null,
                    propertyId: '346',
                    loading: false,
                    timer: null
                },
                {
                    name: '减少',
                    value: null,
                    propertyId: '347',
                    loading: false,
                    timer: null
                },
                {
                    name: '少料-回尾',
                    value: null,
                    propertyId: '348',
                    loading: false,
                    timer: null
                },
                {
                    name: '时间模式-重力筛初始态等待时间',
                    value: null,
                    propertyId: '339',
                    loading: false,
                    timer: null
                },
                {
                    name: '时间模式-重力筛回砻谷机气缸开',
                    value: null,
                    propertyId: '333',
                    loading: false,
                    timer: null
                },
                {
                    name: '时间模式-砻谷出重力筛气缸开',
                    value: null,
                    propertyId: '335',
                    loading: false,
                    timer: null
                },
                {
                    name: '时间模式-白米斗下料气缸关',
                    value: null,
                    propertyId: '338',
                    loading: false,
                    timer: null
                },
            ],
            productInfo: {},
            metadataProperties: [],
            nameToIdMap: {}
        }
    },
    created() {
        if (this.$route.query && this.$route.query.productId) {
            this.productId = this.$route.query.productId
            this.handleViewProduct()
        }
        if (this.$route.query && this.$route.query.deviceId) {
            this.deviceId = this.$route.query.deviceId
        }
    },
    methods: {
        goBack() {
            this.$router.push('/equipment/riceHuskingMachine')
        },
        handleViewProduct() {
            getDeviceProduct(this.productId).then(response => {
                this.productInfo = response.data
                if (this.productInfo.metadata) {
                    try {
                        const metadata = JSON.parse(this.productInfo.metadata)
                        // console.log('meta',metadata)
                        // 获取controlItems中的所有propertyId
                        const validPropertyIds = this.controlItems.map(item => item.propertyId)
                        this.metadataProperties = (metadata.properties || [])
                            .filter(prop => validPropertyIds.includes(prop.id))
                            .map(prop => ({
                                ...prop,
                                value: null
                            }))
                        // console.log('meta',this.metadataProperties)
                        this.createNameToIdMap(this.metadataProperties)
                    } catch (e) {
                        console.error('解析metadata失败:', e)
                        this.metadataProperties = []
                    }
                }
            })
        },
        createNameToIdMap(properties) {
            this.controlItems.forEach(item => {
                const property = properties.find(prop => prop.name === item.name)

                if (property) {
                    item.propertyId = property.id
                }
            })
            this.listInstancePropertyData()
        },
        listInstancePropertyData() {
            listInstanceProperty({ deviceId: this.deviceId }).then(res => {
                const propertyMap = res.data.reduce((acc, item) => {
                    acc[item.propertyId] = item.propertyFormatValue
                    return acc
                }, {})
                this.updateFlowValues(propertyMap)
            })
        },
        updateFlowValues(propertyMap) {
            this.controlItems.forEach(item => {
                const value = propertyMap[item.propertyId]

                if (value !== undefined) {
                    item.value = value === '' ? null : Number(value)
                }
            })
            console.log('con',this.controlItems)
        },
        async handleStepRead({ propertyId, index }) {
            const item = this.controlItems[index]
            item.loading = true

            try {
                const res = await instanceFunctionInvoke({
                    productId: this.productId,
                    deviceId: this.deviceId,
                    functionId: 'modbus-read03',
                    data: {
                        id: propertyId,
                    },
                    clientId: this.webClientId
                })

                if (res.data) {
                    this.sendMessage({
                        'webClientId': this.webClientId,
                        'type': 'login'
                    })
                }

                // 设置定时器
                this.getTimer(index)
            } catch (error) {
                this.resetTime(index)
            }
        },
        async handleStepSubmit({ value, propertyId, index }) {
            const item = this.controlItems[index]
            item.loading = true

            try {
                const res = await instanceFunctionInvoke({
                    productId: this.productId,
                    deviceId: this.deviceId,
                    functionId: 'modbus-write10',
                    data: {
                        id: propertyId,
                        value: value.toString()
                    },
                    clientId: this.webClientId
                })

                if (res.data) {
                    this.sendMessage({
                        'webClientId': this.webClientId,
                        'type': 'login'
                    })
                }

                // 设置定时器
                this.getTimer(index)
            } catch (error) {
                this.resetTime(index)
            }
        },
        resetTime(index) {
            const item = this.controlItems[index]
            item.loading = false
            this.$message.error('系统繁忙，请稍后再试')
        },
        getTimer(index) {
            const item = this.controlItems[index]
            if (item.timer) {
                clearTimeout(item.timer)
            }
            item.timer = setTimeout(() => {
                item.loading = false
                this.$message.error('操作超时，请重试')
            }, 10000)
        },
        sendMessage(obj) {
            if (this.ws !== undefined && this.ws.readyState === 1) {
                console.log('exist')
            } else {
                this.localSocket(obj)
            }
        },
        localSocket(obj) {
            let that = this
            if ('WebSocket' in window) {
                console.log('您的浏览器支持 WebSocket')
                // console.log('that.ws', that.ws)
                if (that.ws !== undefined && that.ws.readyState === 1) {
                    console.log('exist')
                    return
                }

                that.ws = new WebSocket(that.$websocket.url)
                that.$websocket.setWs(that.ws)
                that.ws.onopen = function() {
                    console.log('开始连接')
                    // that.sendMessage(obj)
                    that.$websocket.sendMsg(obj)
                }
                // websocket 接收服务器消息
                that.ws.onmessage = function(result) {
                    console.log('收到websocket回复', result)
                    // console.log('回复data', result.data)
                    that.processData(result.data)
                }
                that.ws.onclose = function() {
                    // 防链接超时，（websocket在一定时间内没有数据交互，就会断开），关闭后重启
                    console.log('连接已关闭')
                    that.ws.close()
                    // setTimeout(() => {
                    //     that.localSocket()
                    // }, 2000)
                }
            } else {
                // 浏览器不支持 WebSocket
                console.log('您的浏览器不支持 WebSocket!')
            }
        },
        processData(json) {
            console.log('json', json)
            if (json === 'ok') {
                console.log('WebSocket连接成功')
                return
            }

            try {
                const data = JSON.parse(json)
                console.log('data', data)
                if (data.webClientId && data.id && data.value !== undefined) {
                    const item = this.controlItems.find(item =>
                        item.propertyId === data.id
                    )

                    if (item) {
                        if (item.timer) {
                            clearTimeout(item.timer)
                            item.timer = null
                        }
                        item.loading = false
                        item.value = parseFloat(data.value)
                        this.$message.success('保存成功')
                    }
                }
            } catch (e) {
                console.error('解析数据失败:', e)
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.app-container {
    padding: 10px;
    background-color: #f5f7fa;
    min-height: 100vh;
}

.page-header {
    margin-bottom: 15px;
    padding: 10px;
    background-color: #fff;
    border-radius: 4px;
}

.control-grid {
   display: flex;
    flex-wrap: wrap;
    gap: 10px;
    justify-content: center;
    padding: 10px;
    background-color: #fff;
    border-radius: 4px;
}

.control-item {
    width: 45%;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    background-color: #fff;

    .item-title {
        font-size: 14px;
        color: #606266;
        text-align: center;
        margin-bottom: 10px;
        font-weight: 500;
    }

    .item-content {
        display: flex;
        gap: 8px;
        align-items: center;

        .el-input-number {
            width: 100%;
        }

    }
}

@media screen and (max-width: 768px) {
    .control-grid {
        grid-template-columns: 1fr;
    }

    .control-item {
        .item-content {
            flex-direction: column;
            align-items: stretch;

            .el-input-number {
                width: 100%;
            }

            .el-button {
                margin-top: 8px;
            }
        }
    }
}
</style>
